import '../css/table.css';
import '../css/news.css';
import ajax from '../js/ajax';
import throttle from '../js/throttle';

const form = document.forms[0];
const list = document.getElementById('list');
const turnpage = document.getElementById('turnPage');
const prev = document.getElementById('prev');
const next = document.getElementById('next');
const current = document.getElementById('current');
let Total_data;
let Total_id;
let currentPage = 1;
let itemCount;
let KeyWord;
let bool;

turnPage();
getNewsClass();
drawTable();
turnPageFix();


//固定切换页按钮
function turnPageFix() {
    let recobj = turnpage.getBoundingClientRect();
    turnpage.style.left = recobj.left + 'px';
    turnpage.style.top = recobj.top + 300 + 'px';
    turnpage.style.right = recobj.right + 'px';
    turnpage.style.bottom = recobj.bottom + 'px';
    turnpage.style.position = 'fixed';
}


//翻页显示
function turnPage() {
    ajax('get', '/api/news/getCount').then(result => {
        if (result.flag) {
            itemCount = result.counts[0].count;
            current.innerHTML = currentPage;
            if (currentPage == 1) {
                prev.disabled = true;
            } else {
                prev.disabled = false;
            }
            if (currentPage == Math.ceil(itemCount / 10)) {
                next.disabled = true;
            } else {
                next.disabled = false;
            }
            prev.onclick = function () {
                if (currentPage == 1) {
                    this.disabled = true;
                    return;
                }
                currentPage--;
                drawTable();
                turnPage();
            }
            next.onclick = function () {
                if (currentPage == itemCount) {
                    this.disabled = true;
                    return;
                }
                currentPage++;
                drawTable();
                turnPage();
            }

        }
    })
}


//搜索新闻
function search_news() {
    if (!bool) {
        bool = true;
        KeyWord = form.searchNews.value;
        drawTable();
        KeyWord = null;
        bool = false;
    }
}


//搜索框输入事件触发请求
form.searchNews.oninput = throttle(search_news, 1000);


//表单提交事件 根据条件判断 触发不同请求 发送不同参数
form.onsubmit = function (e) {
    e.preventDefault();
    let url;
    if (Total_id) {
        url = '/api/admin/modifyNews';
    } else {
        url = '/api/admin/addNews';
    }

    ajax('post', url, {
        classID: form.newsClass.value,
        title: form.title.value,
        content: form.content.value,
        Total_id
    }).then(({ flag, msg }) => {
        if (flag) {
            alert(msg);
            drawTable();
            form.reset();
        } else {
            alert(msg);
        }
    })
}


//dom动态创建表 根据条件判断 触发不同请求 发送不同参数
function drawTable() {
    list.innerHTML = '';
    let url, query;
    if (KeyWord) {
        url = '/api/news/searchNews';
        query = {
            keyword: form.searchNews.value
        }
    } else {
        url = '/api/news/getNews';
        query = {
            currentPage: currentPage
        }
    }
    ajax('get', url, query)
        .then(({ flag, data }) => {
            if (flag) {
                Total_data = data;
                console.log(data)
                data.forEach(item => {
                    const tr = document.createElement('tr');
                    let str = '';
                    str += `<td>${item.id}</td>`;
                    str += `<td>${item.title}</td>`;
                    str += `<td>${item.content}</td>`;
                    str += `<td>${item.classname}</td>`;
                    str += `<td>${item.username}</td>`;
                    str += `<td>${item.createdAt.formatDate('yyyy-MM-dd hh:mm:ss')}</td>`;
                    str += `<td>${item.updatedAt.formatDate('yyyy-MM-dd hh:mm:ss')}</td>`;
                    tr.innerHTML = str;

                    tr.children[1].style.cursor = 'pointer';
                    tr.children[1].onclick = function () {
                        localStorage.setItem('newsid', JSON.stringify(item.id));
                        top.location.assign('newsDetail.html');
                    }
                    tr.children[2].style.cursor = 'pointer';
                    tr.children[2].onclick = function () {
                        localStorage.setItem('newsid', JSON.stringify(item.id));
                        top.location.assign('newsDetail.html');
                    }

                    const td = document.createElement('td');

                    const a = document.createElement('a');
                    a.innerHTML = '修改';
                    a.dataset.id = item.id;
                    td.appendChild(a);
                    a.onclick = modifyNews;

                    const b = document.createElement('a');
                    b.innerHTML = '删除';
                    b.dataset.id = item.id;
                    td.appendChild(b);
                    b.onclick = deleteNews;

                    tr.appendChild(td);
                    list.appendChild(tr);
                });
            } else {
                alert('获取新闻失败');
            }
        })
}


//修改新闻
function modifyNews() {
    Total_id = this.dataset.id;
    let obj;
    Total_data.forEach(item => {
        if (item.id == Total_id) {
            obj = item;
        }
    })
    let child = form.newsClass.children
    for (let i of Object.keys(child)) {
        if (child[i].text == obj.classname) {
            child[i].setAttribute("selected", "true");
        } else {
            child[i].removeAttribute("selected");
        }
    }
    form.title.value = obj.title;
    form.content.value = obj.content;
    form.btn.innerHTML = '修改';
    form.cancel.style.display = 'inline';
}


//删除新闻
function deleteNews() {
    if (!confirm('确定删除此新闻？')) {
        return;
    }
    ajax('post', '/api/admin/deleteNews', { Total_id: this.dataset.id })
        .then(({ flag, msg }) => {
            if (flag) {
                alert(msg);
                drawTable();
            }
        })
}


//获取下拉新闻分类
function getNewsClass() {
    ajax('get', '/api/news/getNewsList').then(({ flag, data }) => {
        if (flag) {
            data.forEach(item => {
                form.newsClass.add(
                    new Option(item.classname, item.id)
                )
            })
        }
    })
}


//取消修改
form.cancel.onclick = back;


function back() {
    form.btn.innerHTML = '新增';
    form.cancel.style.display = 'none';
    Total_id = null;
    form.reset();
}


//改变时间格式
String.prototype.formatDate = function (arg) {
    const date = new Date(this);
    arg = arg.replace('yyyy', date.getFullYear());
    arg = arg.replace('MM', ('0' + (date.getMonth() + 1)).slice(-2));
    arg = arg.replace('dd', ('0' + date.getDate()).slice(-2));
    arg = arg.replace('hh', ('0' + date.getHours()).slice(-2));
    arg = arg.replace('mm', ('0' + date.getMinutes()).slice(-2));
    arg = arg.replace('ss', ('0' + date.getSeconds()).slice(-2));
    return arg;
}